﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WjAutoConfigApp.Common
{
    public class CSVHelper
    {

        /// <summary>
        /// 初始化csv文档
        /// </summary>
        public static async Task InitCSVData(string imageFilePath,int rowNum,int columnNum)
        {
            //开启另外一个线程初始化CSV文档。
            string path = imageFilePath.Replace(@"\", "/");
            string csvPath = path.Substring(0, path.LastIndexOf(@"/")) + "/" + ConstantValue.TRAFFIC_CONFIG;
            await Task.Factory.StartNew(() => InitCSV(csvPath, rowNum, columnNum, ConstantValue.INIT_VALUE));
            return ;
        }

        /// <summary>
        /// 初始画CSV文件
        /// </summary>
        /// <param name="filePath">csv的路径</param>
        /// <param name="rowNum">行数</param>
        /// <param name="columnNum">列数</param>
        /// <param name="content">初始内容</param>
        public static void InitCSV(string filePath, int rowNum, int columnNum, string content = "")
        {
            //存在删除
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            //不存在创建
            if (!File.Exists(filePath))
            {
                using FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            }
            using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default))
            {
                StringBuilder stringBuilder = new StringBuilder();
                //通过枚举的个数初始化csv的内容
                int enumLength = typeof(LanePropertyType).GetEnumValues().Length;
                string str = string.Empty;
                for (int i = 0; i <= enumLength; i++)
                {
                    str += $"{content};";
                }
                content = str.TrimEnd(';');

                for (int i = 0; i < rowNum; i++)
                {
                    stringBuilder.Clear();
                    for (int col = 0; col < columnNum; col++)
                    {

                        stringBuilder.Append(content + ",");
                    }
                    string initLine = stringBuilder.ToString().Trim(',');
                    sw.WriteLine(initLine);
                }
            }
            
        }

        /// <summary>
        /// 设置对应的坐标下CSV的值
        /// </summary>
        /// <param name="p">矩阵坐标点</param>
        /// <param name="csv"></param>
        /// <param name="index">下角标</param>
        /// <param name="value">下标的值</param>
        public static void SetCsvPointValue(Point p, CSV csv, int index, string value)
        {
            var dataValue = csv.GetData(p.Y, p.X);
            var dataArr = dataValue.Split(ConstantValue.PROPERTY_DATA_SPLIT);
            dataArr[index] = value;
            var content = string.Join(ConstantValue.PROPERTY_DATA_SPLIT.ToString(), dataArr);
            csv.SetData(p.Y, p.X, content);
        }

        /// <summary>
        /// 删除车道相关区域信息
        /// </summary>
        /// <param name="areaModel"></param>
        public static void DeleteLaneInfo()
        {
            //0.找到当前车道信息
            var areaModel = GlobleCache.fitAreas.Where(area => area.IsLaneArea).FirstOrDefault();
            if (areaModel is null) 
            {
                CommomMethod.ShowMsg("删除的不是完整车道区域！");
                return; 
            }
            //1.重置此区域对应的车道属性CSV编号信息
            var matchPoints = CommomMethod.GetMatchPoints(areaModel.Points);
            matchPoints.ForEach(p => CSVHelper.SetCsvPointValue(p, GlobleCache.lanePropertyCsv, 0, ConstantValue.INIT_VALUE));
            //2.清空车道CSV信息
            GlobleCache.laneInfoCsv.Clear();
            //3.删除有关此车道的缓存信息
            GlobleCache.areaList.Remove(areaModel);
            //4.重新添加剩余车道CSV信息
            GlobleCache.areaList.Where(area => area.IsLaneArea).ToList().ForEach(model =>
            {
                var value = model.LaneInfoModel.ToString();
                GlobleCache.laneInfoCsv.AddRow(value.Split(';'));
            });
        }

        /// <summary>
        /// 删除车道属性区域
        /// </summary>
        public static void DeleteLanePropertyInfo()
        {
            //0.找到当前车道信息
            var areaModel = GlobleCache.fitAreas.Where(area => !area.IsLaneArea).FirstOrDefault();
            if (areaModel is null)
            {
                CommomMethod.ShowMsg("删除的不是属性区域！");
                return;
            }
            //1.重置此区域对应的车道属性CSV编号信息
            var matchPoints = CommomMethod.GetMatchPoints(areaModel.Points);
            matchPoints.ForEach(p => CSVHelper.SetCsvPointValue(p, GlobleCache.lanePropertyCsv, areaModel.PropertyInfoModel.LanePropertyTypy+1, ConstantValue.INIT_VALUE));
            //2.删除有关此车道的缓存信息
            GlobleCache.areaList.Remove(areaModel);
        }


        /// <summary>
        /// 修改车道信息
        /// </summary>
        public static void EditLaneInfo()
        {
            //2.清空车道CSV信息
            GlobleCache.laneInfoCsv.Clear();
            //3.删除有关此车道的缓存信息
            GlobleCache.areaList.Remove(GlobleCache.areaModel);
            //4.重新添加剩余车道CSV信息
            GlobleCache.areaList.Where(area => area.IsLaneArea).ToList().ForEach(model =>
            {
                var value = model.LaneInfoModel.ToString();
                GlobleCache.laneInfoCsv.AddRow(value.Split(';'));
            });
        }

        /// <summary>
        /// 删除车道属性信息
        /// </summary>
        public static void EditLanePropertyInfo()
        {
            GlobleCache.areaList.Remove(GlobleCache.areaModel);
        }
    }
}
